﻿using EggLink.DanhengServer.Configuration;
using EggLink.DanhengServer.Proto;
using EggLink.DanhengServer.Util;
using EggLink.DanhengServer.WebServer.Handler;
using EggLink.DanhengServer.WebServer.Objects;
using Google.Protobuf;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace EggLink.DanhengServer.WebServer.Controllers;

[ApiController]
[EnableCors("AllowAll")]
[Route("/")]
public class DispatchRoutes
{
    public static ConfigContainer config = ConfigManager.Config;
    public static Logger Logger = new("DispatchServer");

    /// <summary>
    /// 处理客户端请求的API接口，返回调度信息（如服务器列表、网关地址等）。
    /// 客户端通过此接口获取可连接的服务器或网关地址。
    /// </summary>
    /// <returns>Base64编码的调度信息数据</returns>
    [HttpGet("query_dispatch")]
    public string QueryDispatch ()
    {
        var data = new Dispatch();
        data.RegionList.Add(new RegionInfo
        {
            Name = config.GameServer.GameServerId,
            DispatchUrl = $"{config.HttpServer.GetDisplayAddress()}/query_gateway",
            EnvType = "2",
            DisplayName = config.GameServer.GameServerName
        });

        Logger.Info("客户端请求: 查询调度");
        var _response = Convert.ToBase64String(data.ToByteArray());
        Logger.Info($"返回： 原始：{JsonConvert.SerializeObject(data)}  base64：{_response}");

        return _response;
    }

    /// <summary>
    /// 处理风险检查请求，返回固定的安全验证结果
    /// </summary>
    /// <returns>包含风险检查结果的JSON响应</returns>
    [HttpPost("/account/risky/api/check")]
    public ContentResult RiskyCheck ()
    {
        Logger.Info("客户端请求: 风险检查");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":\"none\",\"action\":\"ACTION_NONE\",\"geetest\":null}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    // === AUTHENTICATION ===

    /// <summary>
    /// 处理传统用户名密码登录请求
    /// </summary>
    /// <param name="req">登录请求参数</param>
    /// <returns>登录结果JSON响应</returns>
    [HttpPost("/hkrpg_global/mdk/shield/api/login")]
    public JsonResult Login ([FromBody] LoginReqJson req)
    {
        Logger.Info($"客户端请求: 传统登录 账号:{req.account}");
        var result = new UsernameLoginHandler().Handle(req.account!, req.password!, req.is_crypto);
        Logger.Info($"返回： {JsonConvert.SerializeObject(result.Value)}");
        return result;
    }

    /// <summary>
    /// 处理新版用户名密码登录请求
    /// </summary>
    /// <param name="req">登录请求参数</param>
    /// <returns>登录结果JSON响应</returns>
    [HttpPost("/hkrpg_global/account/ma-passport/api/appLoginByPassword")]
    public JsonResult Login ([FromBody] NewLoginReqJson req)
    {
        Logger.Info($"客户端请求: 新版登录 账号:{req.account}");
        var result = new NewUsernameLoginHandler().Handle(req.account!, req.password!);
        Logger.Info($"返回： {JsonConvert.SerializeObject(result.Value)}");
        return result;
    }

    /// <summary>
    /// 处理令牌验证请求
    /// </summary>
    /// <param name="req">验证请求参数</param>
    /// <returns>验证结果JSON响应</returns>
    [HttpPost("/hkrpg_global/mdk/shield/api/verify")]
    public JsonResult Verify ([FromBody] VerifyReqJson req)
    {
        Logger.Info($"客户端请求: 令牌验证 UID:{req.uid}");
        var result = new TokenLoginHandler().Handle(req.uid!, req.token!);
        Logger.Info($"返回： {JsonConvert.SerializeObject(result.Value)}");
        return result;
    }

    /// <summary>
    /// 处理V2版本登录请求
    /// </summary>
    /// <param name="req">登录请求参数</param>
    /// <returns>登录结果JSON响应</returns>
    [HttpPost("/hkrpg_global/combo/granter/login/v2/login")]
    public JsonResult LoginV2 ([FromBody] LoginV2ReqJson req)
    {
        Logger.Info($"客户端请求: V2登录 AppID:{req.app_id} ChannelID:{req.channel_id}");
        var result = new ComboTokenGranterHandler().Handle(req.app_id, req.channel_id, req.data!, req.device!, req.sign!);
        Logger.Info($"返回： {JsonConvert.SerializeObject(result.Value)}");
        return result;
    }

    /// <summary>
    /// 获取客户端配置信息
    /// </summary>
    /// <returns>包含配置信息的JSON响应</returns>
    [HttpGet("/hkrpg_global/combo/granter/api/getConfig")]
    public ContentResult GetConfig ()
    {
        Logger.Info("客户端请求: 获取配置");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"protocol\":true,\"qr_enabled\":false,\"log_level\":\"INFO\",\"announce_url\":\"\",\"push_alias_type\":0,\"disable_ysdk_guard\":true,\"enable_announce_pic_popup\":false,\"app_name\":\"崩�??RPG\",\"qr_enabled_apps\":{\"bbs\":false,\"cloud\":false},\"qr_app_icons\":{\"app\":\"\",\"bbs\":\"\",\"cloud\":\"\"},\"qr_cloud_display_name\":\"\",\"enable_user_center\":true,\"functional_switch_configs\":{}}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 处理红点提示请求
    /// </summary>
    /// <returns>红点信息JSON响应</returns>
    [HttpGet("/hkrpg_global/combo/red_dot/list")]
    [HttpPost("/hkrpg_global/combo/red_dot/list")]
    public ContentResult RedDot ()
    {
        Logger.Info("客户端请求: 红点提示");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"infos\":[]}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取公告提醒信息
    /// </summary>
    /// <returns>公告提醒JSON响应</returns>
    [HttpGet("/common/hkrpg_global/announcement/api/getAlertAnn")]
    public ContentResult AlertAnn ()
    {
        Logger.Info("客户端请求: 获取公告提醒");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"alert\":false,\"alert_id\":0,\"remind\":false,\"extra_remind\":false}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取公告图片信息
    /// </summary>
    /// <returns>公告图片JSON响应</returns>
    [HttpGet("/common/hkrpg_global/announcement/api/getAlertPic")]
    public ContentResult AlertPic ()
    {
        Logger.Info("客户端请求: 获取公告图片");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"total\":0,\"list\":[]}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 加载客户端配置
    /// </summary>
    /// <returns>配置信息JSON响应</returns>
    [HttpGet("/hkrpg_global/mdk/shield/api/loadConfig")]
    public ContentResult LoadConfig ()
    {
        Logger.Info("客户端请求: 加载配置");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"id\":24,\"game_key\":\"hkrpg_global\",\"client\":\"PC\",\"identity\":\"I_IDENTITY\",\"guest\":false,\"ignore_versions\":\"\",\"scene\":\"S_NORMAL\",\"name\":\"崩�??RPG\",\"disable_regist\":false,\"enable_email_captcha\":false,\"thirdparty\":[\"fb\",\"tw\",\"gl\",\"ap\"],\"disable_mmt\":false,\"server_guest\":false,\"thirdparty_ignore\":{},\"enable_ps_bind_account\":false,\"thirdparty_login_configs\":{\"tw\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"ap\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800},\"fb\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":2592000},\"gl\":{\"token_type\":\"TK_GAME_TOKEN\",\"game_token_expires_in\":604800}},\"initialize_firebase\":false,\"bbs_auth_login\":false,\"bbs_auth_login_ignore\":[],\"fetch_instance_id\":false,\"enable_flash_login\":false}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    // === EXTRA ===

    /// <summary>
    /// 比较协议版本
    /// </summary>
    /// <returns>协议比较结果JSON响应</returns>
    [HttpPost("/hkrpg_global/combo/granter/api/compareProtocolVersion")]
    public ContentResult CompareProtocol ()
    {
        Logger.Info("客户端请求: 比较协议版本");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"modified\":false,\"protocol\":null}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取用户协议信息
    /// </summary>
    /// <returns>协议信息JSON响应</returns>
    [HttpGet("/hkrpg_global/mdk/agreement/api/getAgreementInfos")]
    public ContentResult GetAgreementInfo ()
    {
        Logger.Info("客户端请求: 获取用户协议");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"marketing_agreements\":[]}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取Combo配置信息
    /// </summary>
    /// <returns>Combo配置JSON响应</returns>
    [HttpGet("/combo/box/api/config/sdk/combo")]
    public ContentResult Combo ()
    {
        Logger.Info("客户端请求: 获取Combo配置");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"kibana_pc_config\":\"{ \\\"enable\\\": 0, \\\"level\\\": \\\"Info\\\",\\\"modules\\\": [\\\"download\\\"] }\\n\",\"network_report_config\":\"{ \\\"enable\\\": 0, \\\"status_codes\\\": [206], \\\"url_paths\\\": [\\\"dataUpload\\\", \\\"red_dot\\\"] }\\n\",\"list_price_tierv2_enable\":\"false\\n\",\"pay_payco_centered_host\":\"bill.payco.com\",\"telemetry_config\":\"{\\n \\\"dataupload_enable\\\": 0,\\n}\",\"enable_web_dpi\":\"true\"}}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取预缓存配置
    /// </summary>
    /// <returns>预缓存配置JSON响应</returns>
    [HttpGet("/combo/box/api/config/sw/precache")]
    public ContentResult Precache ()
    {
        Logger.Info("客户端请求: 获取预缓存配置");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"vals\":{\"url\":\"\",\"enable\":\"false\"}}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取设备指纹信息
    /// </summary>
    /// <param name="device_fp">设备指纹参数</param>
    /// <returns>指纹信息JSON响应</returns>
    [HttpGet("/device-fp/api/getFp")]
    public JsonResult GetFp ([FromQuery] string device_fp)
    {
        Logger.Info($"客户端请求: 获取设备指纹 {device_fp}");
        var result = new FingerprintHandler().GetFp(device_fp);
        Logger.Info($"返回： {JsonConvert.SerializeObject(result.Value)}");
        return result;
    }

    /// <summary>
    /// 获取扩展列表
    /// </summary>
    /// <returns>扩展列表JSON响应</returns>
    [HttpGet("/device-fp/api/getExtList")]
    public ContentResult GetExtList ()
    {
        Logger.Info("客户端请求: 获取扩展列表");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"message\":\"OK\",\"data\":{\"code\":200,\"msg\":\"ok\",\"ext_list\":[],\"pkg_list\":[],\"pkg_str\":\"/vK5WTh5SS3SAj8Zm0qPWg==\"}}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }

    /// <summary>
    /// 获取实验列表配置
    /// </summary>
    /// <returns>实验列表JSON响应</returns>
    [HttpPost("/data_abtest_api/config/experiment/list")]
    public ContentResult GetExperimentList ()
    {
        Logger.Info("客户端请求: 获取实验列表");
        var response = new ContentResult
        {
            Content = "{\"retcode\":0,\"success\":true,\"message\":\"\",\"data\":[{\"code\":1000,\"type\":2,\"config_id\":\"14\",\"period_id\":\"6125_197\",\"version\":\"1\",\"configs\":{\"cardType\":\"direct\"}}]}",
            ContentType = "application/json"
        };
        Logger.Info($"返回： {response.Content}");
        return response;
    }
}